package com.htfyun.factorytest.factorytestui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.VolumeUtils;
import com.htfyun.factorytest.R;
import com.htfyun.factorytest.ViewDialogFragment;
import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.common.ForeLightCtrl;
import com.htfyun.factorytest.common.LedCtrl_PX30;
import com.htfyun.factorytest.device.DeviceAttr;
import com.htfyun.factorytest.utils.DebugLog;

public class FactoryFirstActivity extends FactoryBaseActivity {

    private MediaPlayer mediaPlayer;

    //    private final static int MAX_COUNT = 6; //移除了灰阶测试
    private final static int MAX_COUNT = 2;
    private LinearLayout linearLayoutContainer;
    private int[] colorResIds;
    private int currentColorPos;

    private boolean setLongClick = false;

    private final static int MSG_LED_CTRL = 100;
    private final static int PERIOD_LED_CTRL = 800;//1s

    private final static int MSG_FORE_LIGHT_CTRL = 200;
    private final static int PERIOD_FORE_LIGHT_CTRL = 1500;

    private int ledOnCount = 0;
    private int foreLightOnCount = 0;

    private final int HEADSET_PLUG = 0x01;
    private final int HEADSET_UNPLUG = 0x02;
    private int headsetEvent = (HEADSET_PLUG | HEADSET_UNPLUG);
//    private int onFlag = 0;

/*    private ServiceConnection serviceConnection = new MyServiceConnection();
    private FTFloatWindowService mBindService;

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {

            FTFloatWindowService.MyBinder mBinder = (FTFloatWindowService.MyBinder) binder;
            mBindService = mBinder.getService();

            if (mBindService != null) {
                mBindService.setFloatLayoutVisibility(View.INVISIBLE);
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBindService = null;
        }

    }*/

    @Override
    int getLayoutId() {
        return R.layout.activity_factory_first;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

/*        Intent intent = new Intent(this, FTFloatWindowService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);*/

        linearLayoutContainer = findViewById(R.id.linearLayoutContainer);
        colorResIds = getResources().getIntArray(R.array.color_gray_level);

        currentColorPos = 0;

        linearLayoutContainer.removeAllViews();
        linearLayoutContainer.setBackgroundColor(Color.WHITE);

        linearLayoutContainer.setOnClickListener(v -> {
            currentColorPos++;
            if (currentColorPos >= MAX_COUNT) {
                currentColorPos = 0;

                showDialog();
                Toast.makeText(mContext, R.string.screen_test_toast_can_long_click, Toast.LENGTH_LONG).show();

                if (!setLongClick) {
                    setLongClick = true;
                    linearLayoutContainer.setOnLongClickListener(longClickListener);
                }

            }

            if (currentColorPos == 0) {

                linearLayoutContainer.removeAllViews();
                linearLayoutContainer.setBackgroundColor(Color.WHITE);

            } else if (currentColorPos == 1) {

                linearLayoutContainer.removeAllViews();
                linearLayoutContainer.setBackgroundColor(Color.BLACK);

            } /*else {

                final int pos = currentColorPos - 2;
                setChildView((pos & 0x1) != 0, (pos & 0x2) != 0);

            }*/

        });
    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {

        switch (msg.what) {
            case MSG_LED_CTRL:
                if (++ledOnCount > 10000) {
                    ledOnCount = 0;
                }

                if (0 == (ledOnCount % 3)) {
                    LedCtrl_PX30.enableRed();
                } else if (1 == (ledOnCount % 3)) {
                    LedCtrl_PX30.enableGreen();
                } else {
                    LedCtrl_PX30.enableBlue();
                }

/*                if (DeviceAttr.getRunningDeviceAttr().hasForeLight()) {

//                int coldOnFlag = ForeLightCtrl.getForeLightCtrl().getColdLightBrightness() > 0 ? 0x1 : 0;
//                int warmOnFlag = ForeLightCtrl.getForeLightCtrl().getWarmLightBrightness() > 0 ? 0x2 : 0;
//                int onFlag = coldOnFlag | warmOnFlag;
                    if (0 == (ledOnCount % 4)) {
                        ForeLightCtrl.setColdBrightMax(mContext);
                    } else if (1 == (ledOnCount % 4) || 3 == (ledOnCount % 4)) {
                        ForeLightCtrl.setBrightMin(mContext);
                    } else if (2 == (ledOnCount % 4)) {
                        ForeLightCtrl.setWarmBrightMax(mContext);
                    }

                }*/

                handler.sendEmptyMessageDelayed(msg.what, PERIOD_LED_CTRL);

                break;


            case MSG_FORE_LIGHT_CTRL:
                if (++foreLightOnCount > 10000) {
                    foreLightOnCount = 0;
                }
                if (DeviceAttr.getRunningDeviceAttr().hasForeLight()) {
                    if (0 == (foreLightOnCount % 4)) {
                        ForeLightCtrl.setColdBrightMax(mContext);
                    } else if (1 == (foreLightOnCount % 4) || 3 == (foreLightOnCount % 4)) {
                        ForeLightCtrl.setBrightMin(mContext);
                    } else if (2 == (foreLightOnCount % 4)) {
                        ForeLightCtrl.setWarmBrightMax(mContext);
                    }
                }

                handler.sendEmptyMessageDelayed(msg.what, PERIOD_FORE_LIGHT_CTRL);

                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        LedCtrl_PX30.unControlLed();
        Toast.makeText(mContext, R.string.screen_test_toast, Toast.LENGTH_SHORT).show();

        if (DeviceAttr.getRunningDeviceAttr().hasHeadSet()) {
            showDialogForHeadsetTest();

            //发送广播检测耳机插入状态
            IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
            registerReceiver(headsetPlugReceiver, filter);

            startTestPlaySound();
        }

        startLedCtrl();

/*        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.INVISIBLE);
        }*/

    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销广播接收器
        if (DeviceAttr.getRunningDeviceAttr().hasHeadSet()) {
            unregisterReceiver(headsetPlugReceiver);
            stopTestPlaySound();
        }
        stopLedCtrl();

/*        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.VISIBLE);
        }*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        unbindService(serviceConnection);
    }

    private void startLedCtrl() {
        getHandler().sendEmptyMessage(MSG_LED_CTRL);
        getHandler().sendEmptyMessage(MSG_FORE_LIGHT_CTRL);
    }

    private void stopLedCtrl() {
        getHandler().removeMessages(MSG_LED_CTRL);
        getHandler().removeMessages(MSG_FORE_LIGHT_CTRL);
//        LedCtrl.setLed(false, LedCtrl.LedAttr.led_green, LedCtrl.LedAttr.led_red);
        LedCtrl_PX30.unControlLed();
    }

    private void stopTestPlaySound() {

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();//回收资源
            mediaPlayer = null;
        }
    }

    private void startTestPlaySound() {
        if (mediaPlayer != null) {
            stopTestPlaySound();
        }
        try {
            VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, Constants.PCBA_VOLUME, 0);

            mediaPlayer = MediaPlayer.create(getContext(), R.raw.music_test_channel);
            mediaPlayer.setLooping(true);//这种这个后, setOnCompletionListener不能被调用了.
            mediaPlayer.start();
//            mediaPlayer.setVolume(0.5f, 0.5f);
            DebugLog.e("mediaPlayer start ");

        } catch (Exception e) {
            DebugLog.e("exception e = " + e.getMessage());
        }

        mediaPlayer.setOnErrorListener((mp, what, extra) -> {
            DebugLog.e("onError, what = " + what + ", extra = " + extra);
            startTestPlaySound();
            return true;
        });

    }

    private void setChildView(boolean colorRevert, boolean vertical) {

        linearLayoutContainer.removeAllViews();

        linearLayoutContainer.setOrientation(vertical ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);

        for (int i = 0; i < colorResIds.length; i++) {
            View view = new View(mContext);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            int color = colorResIds[i];
            if (colorRevert) {
                color = colorResIds[colorResIds.length - 1 - i];
            }
            view.setBackgroundColor(color);
            view.setClickable(false);
            linearLayoutContainer.addView(view, lp);
        }
    }

    private void showDialog() {
        showFinishDialog(DeviceAttr.getRunningDeviceAttr().hasHeadSet()
                ? R.string.ft_screen_test_dialog_title
                : R.string.ft_screen_test_dialog_title_no_headset, R.string.item_exit_test);
    }

    private View.OnLongClickListener longClickListener =
            v -> {
                showDialog();
                return true;
            };


    ViewDialogFragment dialogWhenHeadsetUnplug;

    private void dismissDialogForHeadsetTest() {

        if (dialogWhenHeadsetUnplug != null) {
            dialogWhenHeadsetUnplug.dismiss();
            dialogWhenHeadsetUnplug = null;
        }
    }

    private void showDialogForHeadsetTest() {

        if (dialogWhenHeadsetUnplug == null) {
            final String title = getString(R.string.headset_event);
            final String msg = getString(R.string.headset_event_plug_unplug);
            dialogWhenHeadsetUnplug = ViewDialogFragment.newInstance(title, msg, false);
        }

        if (!dialogWhenHeadsetUnplug.isShowing()) {
            dialogWhenHeadsetUnplug.show(getFragmentManager());
        }

    }

    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action != null && action.equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {

                    boolean unplug = (intent.getIntExtra("state", 0) == 0);
                    DebugLog.e("unplug = " + unplug);

/*                    if (unplug) {
                        headsetEvent &= ~HEADSET_UNPLUG;
                    } else {
                        headsetEvent &= ~HEADSET_PLUG;
                    }*/
                    headsetEvent &= unplug ? ~HEADSET_UNPLUG : ~HEADSET_PLUG;
                    if (headsetEvent == 0) {
                        dismissDialogForHeadsetTest();
                    }
                }
            }
        }
    };
}
